//
//  OrderHistoryInfoViewController.m
//  OrderAssistant
//
//  Created by chendong on 2020/8/26.
//  Copyright © 2020 chendong. All rights reserved.
//

#import "OrderHistoryInfoViewController.h"
#import "OrderHistoryInfoTableViewCell.h"
#import "NetTools.h"
#import <SVProgressHUD.h>
#import "FCUUID.h"
#import <AFNetworking.h>
@interface OrderHistoryInfoViewController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong) UITableView *myTableView;
@property(nonatomic,strong) NSMutableArray *myTableViewArr;
@property(nonatomic,copy) UILabel *topPriceViewL;
@end

@implementation OrderHistoryInfoViewController
-(UILabel *)topPriceViewL{
    if (!_topPriceViewL) {
        _topPriceViewL = [[UILabel alloc]initWithFrame:CGRectMake(5, kNavBarAndStatusBarHeight, SCREENWIDTH-10, 50)];
        _topPriceViewL.text = @"金额：";
        _topPriceViewL.textAlignment = NSTextAlignmentRight;
        _topPriceViewL.textColor = [UIColor blackColor];
        /// 线的路径
        UIBezierPath * bezierPath = [UIBezierPath bezierPath];
        /// bottom线路径
        [bezierPath moveToPoint:CGPointMake(0.0f, _topPriceViewL.frame.size.height)];
        [bezierPath addLineToPoint:CGPointMake( _topPriceViewL.frame.size.width, _topPriceViewL.frame.size.height)];
        CAShapeLayer * shapeLayer = [CAShapeLayer layer];
            shapeLayer.strokeColor = [UIColor lightGrayColor].CGColor;
            shapeLayer.fillColor  = [UIColor clearColor].CGColor;
            /// 添加路径
            shapeLayer.path = bezierPath.CGPath;
            /// 线宽度
            shapeLayer.lineWidth = 1;
              
            [_topPriceViewL.layer addSublayer:shapeLayer];
//    _topPriceViewL.hidden = [[NSUserDefaults standardUserDefaults] objectForKey:@"IsShowPrice"]?NO:YES;
        NSString *str = [NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"IsShowPrice"]];
        if ([str isEqualToString:@"0"]) {
            _topPriceViewL.hidden = YES;
        }
        [self.view addSubview:_topPriceViewL];
    }
    return _topPriceViewL;
}
-(NSMutableArray *)myTableViewArr{
    if (!_myTableViewArr) {
        _myTableViewArr = [[NSMutableArray alloc]init];
    }
    return _myTableViewArr;
}
-(UITableView *)myTableView{
    if (!_myTableView) {
        if ([[NSUserDefaults standardUserDefaults] objectForKey:@"IsShowPrice"]) {
            NSString *str = [NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"IsShowPrice"]];
            if ([str isEqualToString:@"0"]) {
                _myTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH, SCREENHEIGHT-kTabBarHeight-20) style:UITableViewStylePlain];
            }else{
                _myTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.topPriceViewL.frame), SCREENWIDTH, SCREENHEIGHT-kTabBarHeight-20-CGRectGetMaxY(self.topPriceViewL.frame)) style:UITableViewStylePlain];
            }
//            _myTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.topPriceViewL.frame), SCREENWIDTH, SCREENHEIGHT-CGRectGetMaxY(self.topPriceViewL.frame)) style:UITableViewStylePlain];
//            NSString *str = [NSString stringWithFormat:@"%@",self.dic[@"Amount"]];
//            if ([self.dic[@"Amount"] isKindOfClass:[NSNull class]] || [str isEqualToString:@"0"]) {
//                _myTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH, SCREENHEIGHT) style:UITableViewStylePlain];
//            }else{
//                _myTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.topPriceViewL.frame), SCREENWIDTH, SCREENHEIGHT-CGRectGetMaxY(self.topPriceViewL.frame)) style:UITableViewStylePlain];
//            }
        }else{
            _myTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH, SCREENHEIGHT) style:UITableViewStylePlain];
        }
//        _myTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.topPriceViewL.frame), SCREENWIDTH, SCREENHEIGHT-CGRectGetMaxY(self.topPriceViewL.frame)) style:UITableViewStylePlain];
        _myTableView.dataSource = self;
        _myTableView.delegate = self;
//        _myTableView.backgroundColor = [UIColor blueColor];
        [self.view addSubview:_myTableView];
    }
    return _myTableView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"历史订单详情";
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIView *leftV = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 40, 40)];
    UIButton *gwcBtnl = [UIButton buttonWithType:UIButtonTypeCustom];
    gwcBtnl.frame = CGRectMake(0, 5, 30, 30);
    gwcBtnl.userInteractionEnabled = NO;
    [gwcBtnl setImage:[UIImage imageNamed:@"货框_03.png"] forState:UIControlStateNormal];
    gwcBtnl.imageView.contentMode = UIViewContentModeScaleAspectFit;
    UITapGestureRecognizer *t = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(leftAction:)];
    [leftV addGestureRecognizer:t];
//    [gwcBtnl addTarget:self action:@selector(leftAction:) forControlEvents:UIControlEventTouchUpInside];
    [leftV addSubview:gwcBtnl];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:leftV];
    
    [self myTableView];
    
    [self getData];
}
-(void)leftAction:(UITapGestureRecognizer *)item{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)getData{
    [SVProgressHUD showWithStatus:@"加载中" maskType:SVProgressHUDMaskTypeClear];
    NSDictionary *dic = @{
        @"strOrderId":[NSString stringWithFormat:@"%@",self.dic[@"OrderID"]],
        @"strGroup":@"0"
    };
    NSString *str = [[NSUserDefaults standardUserDefaults] objectForKey:@"ipaddress"];
    if (str.length == 0) {
        // 请求头
//        NSString *accessPath = @"http://192.168.0.19:80/Api/OrderGoods/GetOrderDetails";
        NSString *accessPath = @"http://crm.zhenyea.com/Api/OrderGoods/GetOrderDetails";
        // 请求参数字典
        NSDictionary *params = @{
            @"strOrganizationNo":[NSString stringWithFormat:@"%@",self.userData[@"OrganizationNo"]],
            @"strOrderID":[NSString stringWithFormat:@"%@",self.dic[@"OrderID"]],
            @"strUserId":[NSString stringWithFormat:@"%@",self.userData[@"UserID"]],
            @"strPassword":[NSString stringWithFormat:@"%@",self.userData[@"UserPass"]],
            @"strIMEI":[FCUUID uuidForVendor],
            @"strGroup":@"0"
        };
        
        //创建配置信息
        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
        //设置请求超时时间：5秒
        configuration.timeoutIntervalForRequest = 5;
        //创建会话
        NSURLSession *session = [NSURLSession sessionWithConfiguration: configuration delegate: nil delegateQueue: [NSOperationQueue mainQueue]];
        NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",accessPath]]];
        //设置请求方式：POST
        [request setHTTPMethod:@"POST"];
        [request setValue:@"application/json" forHTTPHeaderField:@"content-Type"];
        [request setValue:@"application/json;charset=gb2312" forHTTPHeaderField:@"Accept"];
        
        //data的字典形式转化为data
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params options:NSJSONWritingPrettyPrinted error:nil];
        //设置请求体
        [request setHTTPBody:jsonData];
        
        NSURLSessionDataTask * dataTask =[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
            [SVProgressHUD dismiss];
            if (error == nil) {
                NSStringEncoding encoding = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
                NSString *receiveStr = [[NSString alloc]initWithData:data encoding:encoding];
                NSData * aData = [receiveStr dataUsingEncoding:NSUTF8StringEncoding];
                NSError *errorr = nil;
                id response = [NSJSONSerialization JSONObjectWithData:aData options:NSJSONReadingMutableContainers error:&errorr];
                if ([response isKindOfClass:[NSDictionary class]]) {
                    // 请求成功数据处理
                    NSString *IsResult = [NSString stringWithFormat:@"%@",[response objectForKey:@"IsResult"]];
                    if ([IsResult isEqualToString:@"1"]) {
                        NSArray *a = response[@"Data"];
//                        if ([self.dic[@"Amount"] isKindOfClass:[NSNull class]]) {
//                            self.topPriceViewL.hidden = YES;
//                        }else{
//                            self.topPriceViewL.hidden = NO;
//                        }
                        self.topPriceViewL.text = [NSString stringWithFormat:@"金额：¥%@",self.dic[@"Amount"]];
                        self.myTableViewArr = [a mutableCopy];
                        [self.myTableView reloadData];
                    }else{
                        [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
                        [SVProgressHUD setMinimumDismissTimeInterval:0.2f];
                        [SVProgressHUD showImage:[UIImage imageNamed:@""] status:[NSString stringWithFormat:@"%@",response[@"Message"]]];
                    }
                } else {
                    [SVProgressHUD showWithStatus:[NSString stringWithFormat:@"%@",response[@"Message"]] maskType:SVProgressHUDMaskTypeClear];
                }
            }else{
                NSData * data = error.userInfo[@"com.alamofire.serialization.response.error.data"];
                NSString * str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
                NSLog(@"服务器的错误原因:%@",str);
                [SVProgressHUD dismiss];
            }
        }];
        [dataTask resume];

//        AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
//
//        NSMutableURLRequest *request = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:accessPath parameters:params error:nil];
//        request.timeoutInterval = 10.f;
//        [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
//        [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
//
//        NSURLSessionDataTask *task = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
//            [SVProgressHUD dismiss];
//            if (!error) {
//                if ([responseObject isKindOfClass:[NSDictionary class]]) {
//                    // 请求成功数据处理
//                    NSString *IsResult = [NSString stringWithFormat:@"%@",[responseObject objectForKey:@"IsResult"]];
//                    if ([IsResult isEqualToString:@"1"]) {
//                        NSArray *a = responseObject[@"Data"];
//                        self.myTableViewArr = [a mutableCopy];
//                        [self.myTableView reloadData];
//                    }else{
//                        [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
//                        [SVProgressHUD setMinimumDismissTimeInterval:0.2f];
//                        [SVProgressHUD showImage:[UIImage imageNamed:@""] status:[NSString stringWithFormat:@"%@",responseObject[@"Message"]]];
//                    }
//                } else {
//                    
//                }
//            } else {
//                NSData * data = error.userInfo[@"com.alamofire.serialization.response.error.data"];
//                NSString * str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
//                NSLog(@"服务器的错误原因:%@",str);
//                [SVProgressHUD dismiss];
//            }
//        }];
//
//        [task resume];
    }else{
        [NetTools postWithUrl:[NSString stringWithFormat:@"http://%@/ldcy/OrderGoods/OrderGoods.asmx/GetOrderDetails",str] pararms:dic
         success:^(id  _Nonnull json) {
            [SVProgressHUD dismiss];
            if ([[NSString stringWithFormat:@"%@",json[@"IsResult"]] isEqualToString:@"1"]) {
                NSArray *a = json[@"Data"];
                self.myTableViewArr = [a mutableCopy];
                [self.myTableView reloadData];
            }else{
                [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
                [SVProgressHUD setMinimumDismissTimeInterval:0.2f];
                [SVProgressHUD showImage:[UIImage imageNamed:@""] status:[NSString stringWithFormat:@"%@",json[@"Message"]]];
            }
        } fail:^(NSError * _Nonnull error) {
            NSData * data = error.userInfo[@"com.alamofire.serialization.response.error.data"];
            NSString * str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"服务器的错误原因:%@",str);
            [SVProgressHUD dismiss];
        }];
    }
    
}
#pragma mark <UITableViewDelegate,UITableViewDataSource>
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.myTableViewArr.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *idf = @"OrderHistoryInfoTableViewCell";
    OrderHistoryInfoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:idf];
    if (!cell) {
        cell = [[OrderHistoryInfoTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:idf];
    }
    cell.dic = self.myTableViewArr[indexPath.row];
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 100;
}
@end
